class Solution {
public:

    TreeNode* build(vector<int>&preordered,vector<int>&inordered,int & prei,int inbegin,int inend)
    {
        if(inbegin>inend)return nullptr;
        
        TreeNode* root=new TreeNode(preordered[prei]);
        int mid=inbegin;
        while(mid<=inend)
        {
            if(inordered[mid]==preordered[prei])break;
            mid++;
        }
        prei++;
        root->left=build(preordered,inordered,prei,inbegin,mid-1);
        root->right=build(preordered,inordered,prei,mid+1,inend);
        return root;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int i=0;
        TreeNode* root=build(preorder,inorder,i,0,inorder.size()-1);
        return root;
    }
};
